Plotting with ggplot2 - Advanced usage

Nina Norgren

Data formats

Input data is always an R data.frame object

[1] "data.frame"
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Geoms

Geoms

library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_point()

Geoms

library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_line()

Geoms

library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_smooth()

Geoms

library(ggplot2)
ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_point()+
       geom_line()+
       geom_smooth()

Aesthetics

Aesthetic mapping vs aesthetic parameter

ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width,
                color='red'))+
       geom_point()

ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_point(aes(color='red'))

Aesthetics

Aesthetic mapping vs aesthetic parameter

ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width,
                color='red'))+
       geom_point()+
       geom_line()

ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width))+
       geom_point(aes(color='red'))+
       geom_line()

Aesthetics

ggplot(iris, aes(x=Sepal.Length,
                 y=Sepal.Width))+
       geom_point(size=3,
                 alpha=0.8,
                 shape=15,
                 color="steelblue")

Aesthetics

ggplot(iris, aes(x=Sepal.Length,
                 y=Sepal.Width))+
       geom_point(aes(size=Petal.Length,
                 alpha=Petal.Width,
                 shape=Species,
                 color=Species))

Scales

  • scales: position, color, fill, size, shape, alpha, linetype
  • syntax: scale_<aesthetic>_<type>
ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width,
                color=Species))+
       geom_point()

ggplot(iris,aes(x=Sepal.Length,
                y=Sepal.Width,
                color=Species))+
       geom_point()+
       scale_color_manual(
           values=c("#5BC0EB","#FDE74C","#9BC53D"))

Facets

  • Split to subplots based on variable(s)
p<-ggplot(iris)+
   geom_point(aes(x=Sepal.Length,
                  y=Sepal.Width,
                  color=Species))
p

p + facet_wrap(~Species)

p + facet_wrap(~Species,nrow=3)